Flash MX Professional 2004 Data Integration Using Microsoft Active Server Pages (ASP)
Table of Contents
ASP Updating the Database with Changes
When ASP detects a call from SaveContacts_xmlcon, Flash is sending the update packet of database changes. The ASP code receives the XML parameters as follows:
if Request("test")="1" then
XMLRequest = false
func = Request("func")
else
XMLRequest = true
Set docReceived = CreateObject("MSXML2.DOMDocument")
docReceived.async = False
docReceived.load Request
Set RequestRoot = docReceived.documentElement
func = RequestRoot.getElementsByTagName("func")(0).text
end if
The else section executes when Flash calls the ASP since Flash
sends no test variable. This code imports the XML
request into the object RequestRoot and derives the func parameter
that specifies which function to perform, a Get or a Save.
When it detects a Save, the process is simply: Loop through the changes in the update packet and execute them against the database. This ASP file performs updates first, then deletes, and finally inserts.
Here is an example of an update packet containing only one record update:
<update_packet tableName="Contacts" nullValue="{_NULL_}" transID="IID74189225305:Fri Jan 23 09:37:01 GMT-0800 2004">
<update id="IID65996659826">
<field name="phone" type="String" oldValue="999-9999xxxx" newValue="999-9999x1234" key="false" />
<field name="contactid" type="Integer" oldValue="116" key="true" />
<field name="email" type="String" oldValue="t@h.com" newValue="t@h.net" key="false" />
<field name="name" type="String" oldValue="Ted" newValue="Teddy" key="false" />
</update>
</update_packet>
There is a list of fields to be updated under each update node in the update packet. One of those fields is the key field that identifies the record ID to be updated; the rest are simply the fields and values to be updated. There is no guarantee what order the fields are in, so the code must loop through them to find the key field itself. Once it has the key field, it loops through the rest of the fields again and builds the SQL update statements for execution.
Here is the ASP code that processes the update nodes:
'PROCESS ALL "UPDATE" NODES
Set UpdateNodes = UP.getElementsByTagName("update")
For Each UpdateNode In UpdateNodes
'CREATE OPERATION RESULT NODE
Set OpElement = ResultsPacket.createElement("operation")
OpElement.SetAttribute "op","update"
OpElement.SetAttribute "id",UpdateNode.getAttribute("id")
Set UpdateFields = UpdateNode.getElementsByTagName("field")
'Must iterate through fields once to get the key id -
' No guarantee what order fields are in (key field not always the first one)
For each UpdateField in UpdateFields
If UpdateField.getAttribute("key") = "true" Then
KeyField = UpdateField.getAttribute("name")
KeyID = UpdateField.getAttribute("oldValue")
Exit For
End If
Next
'Check to see if id field exists, abort ADO call if it doesn't
Dim SendCall
If DBRETURNSERROR then
SendCall = True
Else
If IDExists(Table,KeyField,KeyID) Then
SendCall = True
Else
OpElement.setAttribute "msg",KeyField & " " & KeyID & " does not exist"
SendCall = False
End If
End If
'Second time through For all non-key fields (fields to be updated)
If SendCall then
For each UpdateField in UpdateFields
If UpdateField.getAttribute("key") = "false" Then
fieldname = UpdateField.getAttribute("name")
fieldtype = UpdateField.getAttribute("type")
newfieldvalue = UpdateField.getAttribute("newValue")
If fieldtype <> "Integer" and fieldtype <> "Number" Then
newfieldvalue = "'" & newfieldvalue & "'"
End If
sql = "update " & Table & " Set " & fieldname & "=" & newfieldvalue & " where " & KeyField & "=" & KeyID
On Error Resume Next
cnn.Execute sql
If cnn.Errors.Count > 0 Then
OpElement.SetAttribute "msg",cnn.Errors(0).Description & "/" & sql
cnn.Errors.Clear
End If
On Error Goto 0
End If
Next
End If
'Add Result Element to ResultsPacket
ResultsPacket.lastChild.appendChild OpElement
Next
For a fun (depending on your point of view) advanced project, you could rewrite this segment with one loop instead of two—but who's counting! You could also create the entire SQL statement and execute it just once instead of making a call for each field as I do for this example. This works fine for this illustration, however, so I'll press on.
The last issue in updates is whether or not the database returns an error if the specified key value is not found in the database. Microsoft Access does not report these errors, so you make an initial call to the table before the update just to ensure a record with that key value exists. If it doesn't, then the logic reports an error for that transaction back to Flash. I'll cover the results packet more in the next section.
Here is an example of an update packet containing a delete and an insert:
<update_packet tableName="Contacts" nullValue="{_NULL_}" transID="IID23522107070:Fri Jan 23 09:43:52 GMT-0800 2004">
<delete id="IID19942423282">
<field name="contactid" type="Integer" oldValue="96" key="true" />
</delete>
<insert id="IID35544820130">
<field name="contactid" type="Integer" newValue="" key="true" />
<field name="phone" type="String" newValue="123-456-7890" key="false" />
<field name="email" type="String" newValue="john@xyz.net" key="false" />
<field name="name" type="String" newValue="John" key="false" />
</insert>
</update_packet>
To request deletes, the update packet contains a list of fields under each delete node. Usually there is only one, and it represents the key field. But, just in case, the code loops through and picks out the key. That's all it needs to need to know about the record in question to make the delete SQL call.
Here is the ASP code that processes the delete nodes of the update packet:
'PROCESS ALL "DELETE" NODES
Set DeleteNodes = UP.getElementsByTagName("delete")
For Each DeleteNode In DeleteNodes
'CREATE OPERATION RESULT NODE
Set OpElement = ResultsPacket.createElement("operation")
OpElement.SetAttribute "op","delete"
OpElement.SetAttribute "id",DeleteNode.getAttribute("id")
'FIND KEY FIELD SO WE CAN BUILD SQL STMT
Set DeleteFields = DeleteNode.getElementsByTagName("field")
For each DeleteField in DeleteFields
If DeleteField.getAttribute("key") = "true" Then
KeyField = DeleteField.getAttribute("name")
KeyID = DeleteField.getAttribute("oldValue")
Exit For
End If
Next
'Microsoft Access doesn't report an error when a delete is called for a keyvalue that
'doesn't exist, but since it's already gone from our Flash dataset, we'll just let it
'think that it worked. Other types of errors will still be reported, and dbs that do return
'errors are handled fine.
'Delete from DB
sql = "delete from " & Table & " where " & KeyField & "=" & KeyID
On Error Resume Next
cnn.Execute sql
If cnn.Errors.Count > 0 Then
OpElement.SetAttribute "msg",cnn.Errors(0).Description & "/" & sql
cnn.Errors.Clear
End If
On Error Goto 0
'Add Result Element to ResultsPacket
ResultsPacket.lastChild.appendChild OpElement
Next
Databases like Access do not return an error if you try to delete a record that does not exist. When this happens, since the goal was to remove the record anyway, the code reports the transaction as complete and lets Flash go on its happy way knowing its delete worked. (I won't tell if you won't!) You could easily program any other logic for handling similar situations on your database of choice.
To handle inserts, there is also a list of fields under each insert node in the update packet. In the ASP, you can see how the code loops through the fields, building the insert statement as it goes. At the end, it calls the database. (And you and I hope for the best.)
Here is the ASP code for processing the insert nodes from the update packet:
'PROCESS ALL "INSERT" NODES
Set InsertNodes = UP.getElementsByTagName("insert")
For Each InsertNode In InsertNodes
'CREATE OPERATION RESULT NODE
Set OpElement = ResultsPacket.createElement("operation")
OpElement.SetAttribute "op","insert"
OpElement.SetAttribute "id",InsertNode.getAttribute("id")
'Gather fields to build SQL stmt
Set InsertFields = InsertNode.getElementsByTagName("field")
FieldsStr = ""
ValuesStr = ""
For each InsertField in InsertFields
fieldname = InsertField.getAttribute("name")
fieldtype = InsertField.getAttribute("type")
If InsertField.getAttribute("key") = "false" Then
'NON-KEY FIELD, INCLUDE IN INSERT STMT
newfieldvalue = InsertField.getAttribute("newValue")
If fieldtype = "Integer" or fieldtype = "Number" Then
ValStr = newfieldvalue
Else
ValStr = "'" & newfieldvalue & "'"
End If
If len(ValuesStr) > 0 Then
ValuesStr = ValuesStr & "," & ValStr
Else
ValuesStr = ValStr
End If
If len(FieldsStr) > 0 Then
FieldsStr = FieldsStr & "," & InsertField.getAttribute("name")
Else
FieldsStr = InsertField.getAttribute("name")
End If
Else
'KEY FIELD
KeyField = fieldname
End If
Next
'INSERT TO DB
Identity = ""
If DBRETURNSIDENTITY Then
On Error Resume Next
rs1.Open sql,cnn
If cnn.Errors.Count > 0 Then
OpElement.SetAttribute "msg",cnn.Errors(0).Description & "/" & sql
cnn.Errors.Clear
End If
If rs1.State = adStateOpen Then
rs1.Close
End If
Else
'These statements will work with Microsoft Access - unfortunately, you can't return the identity value
'so you have to do a quick select statement - could cause data collisions in multi-user environment
sql = "insert into " & Table & " (" & FieldsStr & ") values(" & ValuesStr & ")"
On Error Resume Next
cnn.Execute sql
If cnn.Errors.Count > 0 Then
OpElement.SetAttribute "msg",cnn.Errors(0).Description & "/" & sql
cnn.Errors.Clear
Else
End If
End If
On Error Goto 0
'IDENTIFY NEW KEY VALUE FOR THIS NEW RECORD
If Not DBRETURNSIDENTITY Then
'FOR ACCESS, GET LAST KEYFIELD IN DB - NOT GOOD FOR MULTIUSER ENVIRONMENT, ALL WE CAN DO FOR NOW
rs1.open "select top 1 " & KeyField & " from " & Table & " order by " & KeyField & " desc",cnn
Identity = rs1(KeyField)
rs1.close
End If
If Len(Identity) > 0 Then
'PUT IDENTITY IN FIELD NODE
Set IDElement = ResultsPacket.createElement("field")
IDElement.SetAttribute "name",KeyField
IDElement.SetAttribute "curValue",Identity
OpElement.appendChild IDElement
End If
'Add Result Element to ResultsPacket
ResultsPacket.lastChild.appendChild OpElement
Next
Microsoft Access does not return an ID value for autonumber fields like the "big boys" do. You have to make a quick call for the latest ID value from the table so you notify Flash with the ID value for the new record you inserted. This leaves the potential for conflicts in multiuser systems, since other records could be added before your "quick call" executes, returning the wrong ID field. I'll stick with this approach because, while not foolproof, it's easy.
You can see in the ASP file comments that, with just a few changes, you can have this ASP ready for Microsoft SQL Server, which does report back an identity value at the end of an insert call. This would remove the above-mentioned multiuser collision risk.